//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { useStores } from "@/hooks";
import type { ViewInfo } from "@/api/project_dataview";
import { list_view, remove_view } from "@/api/project_dataview";
import { request } from "@/utils/request";
import { Button, Card, Descriptions, List, message, Modal, Popover, Space } from "antd";
import { EditOutlined, MoreOutlined } from "@ant-design/icons";
import EditProjectViewModal from "./compoents/EditProjectViewModal";
import { openDataView } from "@/utils/dataview";
import UserPhoto from "@/components/Portrait/UserPhoto";
import moment from "moment";

const PAGE_SIZE = 24;

export interface ProjectDataViewListProps {
    dataVersion: number;
    projectId: string;
}

const ProjectDataViewList = (props: ProjectDataViewListProps) => {
    const userStore = useStores('userStore');

    const [viewList, setViewList] = useState<ViewInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const [hoverViewId, setHoverViewId] = useState("");
    const [updateInfo, setUpdateInfo] = useState<ViewInfo | null>(null);
    const [removeInfo, setRemoveInfo] = useState<ViewInfo | null>(null);

    const loadViewList = async () => {
        const res = await request(list_view({
            session_id: userStore.sessionId,
            filter_by_project_id: props.projectId != "",
            project_id: props.projectId,
            offset: curPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setViewList(res.view_list);
        setTotalCount(res.total_count);
    };

    const removeView = async () => {
        if (removeInfo == null) {
            return;
        }
        await request(remove_view({
            session_id: userStore.sessionId,
            project_id: removeInfo.project_id,
            view_id: removeInfo.view_id,
        }));
        message.info("删除成功");
        setRemoveInfo(null);
        await loadViewList();
    };

    useEffect(() => {
        if (curPage != 0) {
            setCurPage(0);
        } else {
            loadViewList();
        }
    }, [props.dataVersion, props.projectId]);

    useEffect(() => {
        loadViewList();
    }, [curPage]);

    return (
        <>
            <List rowKey="view_id" dataSource={viewList} grid={{ gutter: 16 }}
                pagination={{ total: totalCount, pageSize: PAGE_SIZE, current: curPage + 1, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }}
                renderItem={item => (
                    <List.Item>
                        <Card title={<a style={{ color: "black" }} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            openDataView(item.view_id, item.title, item.project_id);
                        }}>{item.title}</a>}
                            style={{ backgroundColor: item.bg_color, width: "300px", boxShadow: "6px 6px 5px 0px #777", borderRadius: "10px" }}
                            headStyle={{ border: "none", fontSize: "20px", fontWeight: 600, textOverflow: "ellipsis", overflow: "hidden", whiteSpace: "nowrap" }}
                            bodyStyle={{ height: "170px", padding: "0px 10px" }}
                            onMouseEnter={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setHoverViewId(item.view_id);
                            }}
                            onMouseLeave={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setHoverViewId("");
                            }}
                            extra={
                                <Space>
                                    {hoverViewId == item.view_id && (
                                        <Button type="text" icon={<EditOutlined />} onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            setUpdateInfo(item);
                                        }} disabled={item.user_perm.can_update == false} />
                                    )}
                                    <Popover placement="bottom" trigger="click" content={
                                        <Space direction="vertical">
                                            <Button type="link" onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setUpdateInfo(item);
                                            }} disabled={item.user_perm.can_update == false} >修改</Button>
                                            <Button type="link" danger onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setRemoveInfo(item);
                                            }} disabled={item.user_perm.can_remove == false}>删除</Button>
                                        </Space>
                                    }>
                                        <MoreOutlined />
                                    </Popover>
                                </Space>
                            }>

                            <div style={{ cursor: "pointer" }} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                openDataView(item.view_id, item.title, item.project_id);
                            }}>
                                <Descriptions column={1} labelStyle={{ fontSize: "16px" }} contentStyle={{ fontSize: "16px" }} >
                                    <Descriptions.Item label="创建者">
                                        <Space>
                                            <UserPhoto logoUri={item.owner_logo_uri} style={{ width: "16px", borderRadius: "10px" }} />
                                            {item.owner_display_name}
                                        </Space>
                                    </Descriptions.Item>
                                    <Descriptions.Item label="创建时间">
                                        {moment(item.create_time).format("YYYY-MM-DD")}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="备注信息">
                                        <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word", height: "100px", overflowY: "scroll",width:"100%" }}>
                                            {item.desc}
                                        </pre>
                                    </Descriptions.Item>
                                </Descriptions>
                            </div>
                        </Card>
                    </List.Item>
                )} />

            {updateInfo != null && (
                <EditProjectViewModal viewInfo={updateInfo} onCancel={() => setUpdateInfo(null)} onOk={() => {
                    setUpdateInfo(null);
                    loadViewList();
                }} />
            )}
            {removeInfo != null && (
                <Modal open title="删除项目视图" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeView();
                    }}>
                    是否删除项目视图&nbsp;{removeInfo.title}&nbsp;?
                </Modal>
            )}
        </>
    );
};

export default observer(ProjectDataViewList);